package com.springboot.controller;

import com.springboot.model.ProductCategory;
import com.springboot.model.ProductInfo;
import com.springboot.service.CategoryService;
import com.springboot.service.ProductService;
import com.springboot.vo.ProductInfoVo;
import com.springboot.vo.ProductVo;
import com.springboot.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;


    @GetMapping("/list")
    public ResultVo list() {
        //1.查询所有的上架的商品
        List<ProductInfo> productInfoList = productService.findAll();
        //2.查询类目
        List<Integer> typeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        //传统写法 foreach

        //java8 lamdba
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(typeList);

        //3.数据拼接
        List<ProductVo> productVoList=new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList) {
            ProductVo productVo = new ProductVo();
            productVo.setCategoryName(productCategory.getCategoryName());
            productVo.setCategoryType(productCategory.getCategoryType());

            List<ProductInfoVo> productInfoVos = new ArrayList<>();
            for (ProductInfo productInfo :
                    productInfoList) {
                if (productCategory.getCategoryType().equals(productInfo.getCategoryType())) {
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo, productInfoVo);
                    productInfoVos.add(productInfoVo);
                }
            }
            productVo.setData(productInfoVos);
            productVoList.add(productVo);
        }
        ResultVo resultVo = new ResultVo();
        resultVo.setData(productVoList);
        resultVo.setCode(0);
        resultVo.setMsg("成功");
        return resultVo;
    }


}
